﻿using System.Collections.Generic;

namespace Pisces
{
	/*
	 * created by wangqiang
	 */
	public abstract class AbstractLogicEntity : AbstractEntity
	{
		/// <summary>
		/// entity的所有模块集合
		/// </summary>
		private List<AbstractEntityModule> entityModules = new List<AbstractEntityModule>();
	    
        
		/// <summary>
		/// 注册entity模块
		/// </summary>
		/// <typeparam name="T"> entity 类型 </typeparam>
		/// <returns></returns>
		protected T registerEntityModule<T>() where T : AbstractEntityModule, new()
		{
			T module = getEntityModule<T>();
			if (module != null)
			{
				return module;
			}
			
			module.HostEntity = this;
			entityModules.Add(module);
			
			module.onInit();
			
			return module;
		}

		/// <summary>
		/// 根据泛型获取所持有的moudle实例
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		protected T getEntityModule<T>() where T : AbstractEntityModule
		{
			int count = entityModules.Count;
			for (int i = 0; i < count; i++)
			{
				AbstractEntityModule module = entityModules[i];
				if (module == null)
				{
					continue;
				}

				if (module.GetType() == typeof(T))
				{
					return (T) module;
				}
			}

			return null;
		}

		/// <summary>
		/// 删除一个entity模块
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		protected AbstractEntityModule removeEntityModule<T>() where T : AbstractEntityModule
		{
			AbstractEntityModule removedObject = null;
			int count = entityModules.Count;
			for (int i = 0; i < count; i++)
			{
				removedObject = entityModules[i];
				if (removedObject == null)
				{
					continue;
				}

				if (removedObject.GetType() == typeof(T))
				{
					entityModules.RemoveAt(i);
					break;
				}
			}

			return removedObject;
		}

		public override void onAwake()
		{
			base.onAwake();

			int count = entityModules.Count;
			for (int i = 0; i < count; i++)
			{
				entityModules[i].onAwake();
			}
		}

		public override void onUpdate(float deltaTime)
		{
			base.onUpdate(deltaTime);
		    
			int count = entityModules.Count;
			for (int i = 0; i < count; i++)
			{
				entityModules[i].onUpdate(deltaTime);
			}
		    
		}

		public override void onDestroy()
		{
			base.onDestroy();
			
			int count = entityModules.Count;
			for (int i = 0; i < count; i++)
			{
				entityModules[i].onDestroy();
			}
		}
	}
}